import struct
import socket
from PIL import ImageGrab
from cv2 import cv2
import numpy as np
import threading

bufsize = 1024

host = ('0.0.0.0', 8080)
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.bind(host)
soc.listen(1)
img = None

def handle(conn):
    global img
    img = np.asarray(ImageGrab.grab())
    _, imb = cv2.imencode('.png', img)
    lenb = struct.pack('>I', len(imb))
    conn.sendall(lenb)
    conn.sendall(imb)
    while True:
        cv2.waitKey(100)
        gb = ImageGrab.grab()
        imgnpn = np.asarray(gb)
        subn = imgnpn - img
        if (subn != 0).any():
            pass
        else:
            continue
        img = imgnpn
        _, imb = cv2.imencode('.png', subn)
        dlen = len(imb)
        lenb = struct.pack('>I', dlen)
        try:
            conn.sendall(lenb)
            conn.sendall(imb)
        except:
            print('连接中断...')
            return


if __name__ == '__main__':
    while True:
        conn, addr = soc.accept()
        handle(conn)
        # sub_thread = threading.Thread(target=handle, args=(conn, ))
        # sub_thread.start()